package com.partner.dao;

import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.google.gson.Gson;
import com.partner.domain.GroupUser;
import com.partner.domain.User;
import com.partner.domain.UserAndGroup;
import com.partner.domain.Yaoqingfriend;
import com.partner.util.ApiHttpClient;
import com.partner.util.DBUtil;

/**
 * 群组的dao
 * @author Jinshuan
 *
 */
public class GroupDao {
	QueryRunner queryRunner_auto = new QueryRunner(DBUtil.getDataSource());
	QueryRunner queryRunner_self = new QueryRunner();
	
	//先将这个群在融云的服务器上建立
	String key = "y745wfm84aiev";//替换成您的appkey
	String secret = "w8BcXexdSfghg";//替换成匹配上面key的secret
	//创建群
	public boolean createGroup(String groupName,String userid,String photo,String qunzhu,String nickname){
		//先将目前的最大的groupid给查到
		String groupId = getGroupId();
		if(groupId!=null){
			groupId = (Integer.parseInt(groupId)+1)+"";
		}else{
			groupId = "10000000";
		}
		String sql = "insert into groups values(?,?,?,?,?,?)";
		Object[] params = {groupId,groupName,userid,photo,qunzhu,nickname};
		

		SdkHttpResult result = null;
		List<String> userIds = new ArrayList<String>();
		userIds.add(userid);
		
//		//创建群
		try {
			result = 	ApiHttpClient.createGroup(key, secret, userIds, groupId, groupName, FormatType.json);
			System.out.println(result);
			//根据返回结果来
			if(result.getHttpCode()==200){
				System.out.println("成功回来");
				if(queryRunner_auto.update(sql, params)>0){
					return true;
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return false;
		}
		
	
				
		return false;
	}
	
	//查询用户所有的群
	public List<UserAndGroup> selectUserBelongGroup(String userId){
		String sql = "select * from groups where userid = ?";
		Object[] params = {userId};
		try {
			List<UserAndGroup> userAndGroups = queryRunner_auto.query(sql, new BeanListHandler<UserAndGroup>(UserAndGroup.class),params);
			if(userAndGroups!=null){
				return userAndGroups;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
			
	}
	
	public String getGroupId(){
		String sql = "select MAX(groupId) from  groups";
		try {
			String groupId = (String) queryRunner_auto.query(sql, new ScalarHandler(1));
			return groupId;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//得到群内所有用户
	public List<GroupUser> getGroupUser(String groupId,String phone){
		//这里如果是好友的话并且有备注，就显示好友备注，否，则如果有群昵称，就显示群昵称，否，就显示用户名
		String sql = "select groups.userid,groups.qunzhu,groups.nickname,`user`.photo as img,`user`.`year`,`user`.zhuanye,`user`.school,`user`.username from groups,`user` where groupId = ? and `user`.phone = groups.userid and user.phone !=?";
		Object[] params = {groupId,phone};
		try {
			List<GroupUser>  groupUsers = queryRunner_auto.query(sql, new BeanListHandler<GroupUser>(GroupUser.class), params);
			if(groupUsers!=null){
				for(GroupUser groupUser:groupUsers){
					String sql2 = "select nickname from friend where uid = ? and fid = ?";
					Object[] params2 = {phone,groupUser.getUserid()};
					String nicheng = (String) queryRunner_auto.query(sql2, new ScalarHandler(1), params2);
					String sql3 = "select state from friend where uid = ? and fid = ?";
					String state = (String) queryRunner_auto.query(sql3, new ScalarHandler(1), params2);
					if(nicheng!=null){
						groupUser.setIsFriend(state);
						if(!(" ".equals(nicheng))||!("".equals(nicheng))){
							//如果是好友且有备注就显示备注
							groupUser.setNickname(nicheng);
						}
						
					}else{
						groupUser.setIsFriend("4");
					}
				}
			}
			return groupUsers;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	//邀请好友加入群里.这时是往邀请好友加入群表里插入数据
	public boolean yaoqingFriend(String from,String[] tos,String groupId){
		//可能一下子邀请多个好友
		String sql = "insert into yaoqingfriend VALUES(?,?,?)";
		boolean result = true;
		
		List<Yaoqingfriend> yaoqingfriends = selectYaoqingData();
		//其实这里应该是用事务的。
		for(int i=0;i<tos.length;i++){
			String to = tos[i];
			//这里判断一下这个表中有没有这个数据
			Object[] params = {from,to,groupId};
			boolean zhongjian = false;
			//如果现在有这条邀请数据就不在数据库插入了。不然会报主键重复错误
			for(Yaoqingfriend yaoqingfriend:yaoqingfriends){
				if(yaoqingfriend.getTo_who().equals(to)&&yaoqingfriend.getGroupId().equals(groupId)){
					zhongjian = true;
					break;
				}
			}
			//如果现在数据里没有含这条数据就去插入数据
			if(!zhongjian){
				try {
					if(queryRunner_auto.update(sql, params)>0){
						//加入成功就返回true
					}else{
						result = false;
					}
				} catch (SQLException e) {
					e.printStackTrace();
					return false;
				}
			}
			
		}
		return result;
//		String sql = "insert into friend VALUES(?,?,?,?,?)";
//		Object[] params = {from,to,groupId,6,""};t
//		return false;
	}
	
	//查询一下现在里面有哪些邀请数据
	public List<Yaoqingfriend> selectYaoqingData(){
		String sql = "select * from yaoqingfriend";
		List<Yaoqingfriend> yaoqingfriends = new ArrayList<Yaoqingfriend>();
		try {
			 yaoqingfriends = queryRunner_auto.query(sql, new BeanListHandler<Yaoqingfriend>(Yaoqingfriend.class));
			 if(yaoqingfriends==null){
				 yaoqingfriends = new ArrayList<Yaoqingfriend>();
			 }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return yaoqingfriends;
		
	}
	//同意加入群
	public boolean argeeIntoGroup(String userId, String groupId, String groupName,String photo,String qunzhu,String nickname,String from_who){
//		boolean result = false;
		//先将这个群成员加到融云的服务器上
		String sql = "insert into groups value(?,?,?,?,?,?)";
		Object[] params = {groupId,groupName,userId,photo,qunzhu,nickname};
		
		
		SdkHttpResult result = null;
		try {
			result = 	ApiHttpClient.joinGroup(key, secret, userId, groupId, groupName, FormatType.json);
			System.out.println(result);
			//根据返回结果来
			if(result.getHttpCode()==200){
				System.out.println("成功回来");
				//融云上加入成功之后。就先删除邀请数据。然后在groups中加入数据
				if(delineYaoqingTongZhi(from_who, userId, groupId)){
					
					if(queryRunner_auto.update(sql, params)>0){
						return true;
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	return false;
		
	}
	//明确拒绝加入对应的群,就是在自己服务器上删掉
	public boolean delineYaoqingTongZhi(String from_who,String to_who,String groupId){
		boolean result = true;
		String sql = "delete from yaoqingfriend where from_who = ? and to_who=? and groupId = ?";
		Object[] params = {from_who,to_who,groupId};
		System.out.println(from_who+"--"+to_who+"--"+groupId);
		try {
			if(queryRunner_auto.update(sql, params)<=0){
				System.out.println("删除对应的yaoqingfriend--"+result);
				result = false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
